package com.example.weiwing.home.calendar;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.bumptech.glide.Glide;
import com.example.weiwing.EditProfileActivity;
import com.example.weiwing.R;
import com.example.weiwing.config.WeiWingConfig;
import com.example.weiwing.entity.Article;
import com.example.weiwing.home.dynamic.DynamicView;
import com.example.weiwing.util.ChooseVideoOrPictureUtils;
import com.example.weiwing.util.SpUtils;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.XXPermissions;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.JsonMap;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.List;


public class CalendarFragment extends Fragment {
    private static final String TAG = "CALENDARFRAGMENT";
    private Button dynamicPublic;
    private ImageView imageView;
    private View view;
    private String imageFilePath;
    private Uri saveUri;
    private EditText title;
    private EditText content_text;
    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private static final int REQUEST_SELECT_IMAGE = 2;
    private Handler imgHandler;
    private String mSelectType;
    private String imgPath;
    private String imagePath;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_calendar, container, false);
        dynamicPublic = (Button) view.findViewById(R.id.calendarDynamicPublic);
        imageView = (android.widget.ImageView) view.findViewById(R.id.imageDynamicAdd);
        title = (EditText) view.findViewById(R.id.calendarDynamicTitle);
        content_text = (EditText) view.findViewById(R.id.calendarDynamicText);

        imgHandler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {
                    JSONObject jsonObject = JSON.parseObject((String) msg.obj);
                    if (jsonObject.getInteger("code") == 200) {
                        imgPath = jsonObject.getString("imgPath");
                        Toast.makeText(getActivity(), "上传成功", Toast.LENGTH_SHORT).show();
                    } else if (jsonObject.getInteger("code") == 500) {
                        // 图片上传失败
                        String rmsg = jsonObject.getString("msg");
                        Toast.makeText(getActivity(), rmsg, Toast.LENGTH_SHORT).show();
                    }

                }

            }
        };


        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        dynamicPublic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                if (title.getText().toString().trim().isEmpty()) {
                    Toast.makeText(requireContext(), "标题不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                Drawable drawable = imageView.getDrawable();
                Drawable expectedDrawable = ContextCompat.getDrawable(requireContext(), R.drawable.baseline_add_24);
                if (drawable.getConstantState().equals(expectedDrawable != null ? expectedDrawable.getConstantState() : null)) {
                    Toast.makeText(requireContext(), "请添加图片", Toast.LENGTH_SHORT).show();
                } else {
                    // 当前图片与特定资源图片不同
                    // 在这里编写相应逻辑
//                        publish(String title, String content);
                    publish();
                }
            }

        });

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showImageSelectionDialog();
            }
        });
    }

    private void showImageSelectionDialog() {
        final CharSequence[] options = {"选择图片", "取消"};

        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("选择操作");

        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals("选择图片")) {
                    // 启动从相册选择照片 Intent
                    choosePicture();

                    //Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    //startActivityForResult(pickPhoto, REQUEST_SELECT_IMAGE);
                } else if (options[item].equals("取消")) {
                    dialog.dismiss();
                }
            }
        });

        builder.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST && resultCode == RESULT_OK) {
//                selectedImageUri = data.getData();
//                imageView.setImageURI(selectedImageUri);
//                String[] proj = {MediaStore.Images.Media.DATA};
//                Cursor cursor = getActivity().getContentResolver().query(selectedImageUri, proj, null, null, null);
//                if (cursor.moveToFirst()) {
//                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//                    imageFilePath = cursor.getString(column_index);
//                }
//                cursor.close();
            if ("image".equals(mSelectType)) {
                List<LocalMedia> mLocalImageVideo = PictureSelector.obtainMultipleResult(data);
                if (!TextUtils.isEmpty(mLocalImageVideo.get(0).getCutPath())) {
                    imagePath = mLocalImageVideo.get(0).getCutPath();
                } else {
                    imagePath = mLocalImageVideo.get(0).getRealPath();
                }

                if (!TextUtils.isEmpty(imagePath)) {
                    Glide.with(getActivity()).load(imagePath).into(imageView);
                    File file = new File(imagePath);
                    uploadImg(file);
                } else {
                    Toast.makeText(getActivity(), "上传失败", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }

    private void uploadImg(File file) {
        ProgressDialog progressDialog = ProgressDialog.show(getActivity(), "请稍候", "上传图片...");

        new Thread(() -> HttpRequest.build(getActivity(), WeiWingConfig.getUrl() + "/article/uploadImage")
                .setAsync(true)
                .addHeaders("token", SpUtils.getString(getActivity(), "token"))
                .addParameter("image", file).setResponseListener(new ResponseListener() {
                    @Override
                    public void onResponse(String response, Exception error) {
                        progressDialog.dismiss();
                        if (error == null) {
                            imgHandler.obtainMessage(1, response).sendToTarget();
                        } else {
                            Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }).doPost()).start();
    }


    public void publish() {
        ProgressDialog progressDialog = ProgressDialog.show(getActivity(), "WEI_WING", "发布中...");
        JsonMap jsonMap = new JsonMap();
        jsonMap.set("title", title.getText().toString());
        jsonMap.set("content", content_text.getText().toString());
        jsonMap.set("imgUrl", imgPath);
        new Thread(() -> HttpRequest.build(getActivity(), WeiWingConfig.getUrl() + "/article/publish")
                .setAsync(true)
                .addHeaders("token", SpUtils.getString(getActivity(), "token"))
                .setJsonParameter(jsonMap)
                .setResponseListener(new ResponseListener() {
                    @Override
                    public void onResponse(String response, Exception error) {
                        progressDialog.dismiss();
                        if (error == null) {
                            JSONObject jsonObject = JSON.parseObject(response);
                            if (jsonObject.getInteger("code") == 200) {
                                String articleId = jsonObject.getString("data");
                                Toast.makeText(getActivity(), "发布成功", Toast.LENGTH_SHORT).show();
                                afterPublish(articleId);
                                // TODO: 发布成功后的页面处理，转跳...
                            } else {
                                Toast.makeText(getActivity(), "未知错误", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(getActivity(), "发布失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }).doPost()).start();
    }

    public void afterPublish(String articleId) {
        title.setText("");
        content_text.setText("");
        imageView.setImageResource(R.drawable.baseline_add_24);

        imageFilePath = null;
        saveUri = null;
        imgPath = null;

        View dynamic = getActivity().findViewById(R.id.dynamic);
        dynamic.callOnClick();

        Intent it = new Intent(getActivity(), DynamicView.class);
        it.putExtra("articleId", articleId);
        startActivity(it);

    }

    private void choosePicture() {
        XXPermissions.with(getActivity())
                .permission(android.Manifest.permission.CAMERA, android.Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> list, boolean b) {
                        //选择视频
                        mSelectType = "image";
                        ChooseVideoOrPictureUtils.PictureShoot(getActivity());
                    }

                    @Override
                    public void noPermission(List<String> list, boolean b) {
                    }
                });
    }

}